package j2EE.factory;

import j2EE.servlet.ResourceFactory;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Created with Intel IDEA.
 *
 *  xml 解析工厂 类似数据库连接
 * @Auther: gjt
 * @Date: 2024/11/30 16:20
 */
public class XMLParserFactory implements ResourceFactory {
    DocumentBuilderFactory dbf;

    public XMLParserFactory( ) {
        this.dbf = DocumentBuilderFactory.newInstance();
    }

    // 创建以一个新的DocumentBuilder 来添加到池中
    @Override
    public Object createResource() {
        try {
            return dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *  检查返回的DocumentBuilder 为有效的 并将参数复位到默认值
     * @param o
     * @return
     */
    @Override
    public boolean validateResource(Object o) {
        if(! (o instanceof DocumentBuilder)){
            return false;
        }
        DocumentBuilder documentBuilder = (DocumentBuilder) o;
        documentBuilder.setEntityResolver(null);
        documentBuilder.setErrorHandler(null);
        return true;
    }

}
